<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router' // 引入 useRouter
import { Api } from '@/api'
import { ElMessage } from 'element-plus'
import {baseURL} from '@/utils/request.js'
//import { Icon } from 'vant'

defineOptions({
  name: 'ArticleDetailPage',
})

const route = useRoute()
const router = useRouter() // 使用 useRouter
const article = ref(null)
const loading = ref(true)
const error = ref(null)
const liked = ref(false) // 用于切换爱心图标的状态

// 获取文章详情
const fetchArticle = async () => {
  try {
    const payload = { id: route.params.id }
    console.log('发送到后端的请求数据:', payload)

    const response = await Api.getPsychologyKnowledgeById(payload)
    console.log('后端返回的数据:', response.data) // 添加日志
    
    if (response.data.status === 200 && response.data.data) {
      const articleData = response.data.data
      // 解析图片字段
      let pictures = []
      try {
        pictures = JSON.parse(articleData.picture || '[]')
        console.log('解析后的图片数组:', pictures) // 添加日志
      } catch (e) {
        console.error('解析图片字段失败:', e)
      }
      
      article.value = {
        ...articleData,
        pictures: pictures.map(url => url.startsWith('http') ? url : `${baseURL}${url}`)
      }
      console.log('处理后的文章数据:', article.value) // 添加日志
    } else {
      error.value = response.data.message || '文章不存在'
      console.error('文章数据获取失败:', response.data) // 添加日志
    }
  } catch (err) {
    error.value = '获取文章详情失败'
    console.error('Error fetching article:', err)
  } finally {
    loading.value = false
  }
}

// 点赞功能
const likeArticle = async () => {
  try {
    const response = await Api.likePsychologyKnowledge({ id: route.params.id })
    if (response.data.status === 200) {
      article.value.likes += 1 // 本地更新点赞数
      liked.value = true
      ElMessage.success('点赞成功')
    } else {
      ElMessage.error(response.data.message || '点赞失败')
    }
  } catch (err) {
    console.error('点赞失败:', err)
    ElMessage.error('点赞失败，请稍后再试')
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

onMounted(() => {
  fetchArticle()
})
</script>

<template>
  <div class="article-detail-page">
    <!-- 返回按钮 -->
    <div class="back-button" @click="goBack">
      <van-icon name="arrow-left" class="back-icon" /> 返回
    </div>

    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <div v-else-if="article" class="article-content">
      <div class="article-header">
        <h1 class="article-title">{{ article.title }}</h1>
        <div class="article-tags">
          <span v-for="tag in article.tags" :key="tag" class="tag">{{ tag }}</span>
        </div>
      </div>
      <div class="article-body">
        <!-- 渲染图片 -->
        <div class="article-images" v-if="article.pictures && article.pictures.length > 0">
          <img
            v-for="(picture, index) in article.pictures"
            :key="index"
            :src="picture"
            :alt="'图片' + (index + 1)"
            class="article-image"
          />
        </div>
        <p class="article-description">{{ article.description }}</p>
        <div class="article-text" v-html="article.content"></div>
      </div>
      <div class="article-footer">
        <div class="article-stats">
          <span>点赞：{{ article.likes }}</span>
        </div>
        <div class="article-likes">
          <button
            class="like-button"
            :class="{ liked }"
            @click="likeArticle"
          >
            <van-icon :name="liked ? 'like' : 'like-o'" class="like-icon" />
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.article-detail-page {
  max-width: 800px;
  margin: 60px auto;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.back-button {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  font-size: 16px;
  color: #4caf50;
  font-weight: bold;
  margin-bottom: 20px;
}

.back-button:hover {
  color: #388e3c;
}

.back-icon {
  font-size: 20px;
}

.loading,
.error {
  text-align: center;
  padding: 40px;
  font-size: 1.2rem;
}

.error {
  color: #ff4444;
}

.article-header {
  text-align: center;
  margin-bottom: 20px;
}

.article-title {
  font-size: 2rem;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

.article-tags {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 10px;
}

.tag {
  background: #e0f7fa;
  color: #00796b;
  padding: 5px 10px;
  border-radius: 20px;
  font-size: 0.9rem;
}

.article-body {
  margin-bottom: 20px;
}

.article-image {
  width: 100%;
  max-height: 400px;
  object-fit: cover;
  border-radius: 8px;
  margin-bottom: 20px;
}

.article-description {
  font-size: 1.1rem;
  color: #666;
  margin-bottom: 20px;
  line-height: 1.6;
}

.article-text {
  font-size: 1rem;
  line-height: 1.8;
  color: #333;
  white-space: pre-line;
}

.article-footer {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.article-stats {
  font-size: 1rem;
  color: #666;
}

.article-likes {
  display: flex;
  align-items: center;
  gap: 10px;
}

.like-button {
  width: 50px;
  height: 50px;
  border: none;
  border-radius: 50%;
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.like-button:hover {
  background-color: #ffecec;
  transform: scale(1.1);
}

.like-button.liked {
  background-color: #ffecec;
  animation: liked-animation 0.3s ease;
}

.like-icon {
  font-size: 24px;
  color: gray;
  transition: color 0.3s ease;
}

.like-button.liked .like-icon {
  color: red;
}

@keyframes liked-animation {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.3);
  }
  100% {
    transform: scale(1);
  }
}

@media (max-width: 768px) {
  .article-detail-page {
    margin: 20px auto;
    padding: 10px;
  }

  .article-title {
    font-size: 1.5rem;
  }

  .article-description {
    font-size: 1rem;
  }

  .article-text {
    font-size: 0.9rem;
  }

  .like-button {
    width: 40px;
    height: 40px;
  }

  .like-icon {
    font-size: 20px;
  }
}
</style>
